package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.jxc.abstracts.AbstractJxcUpdateDataService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.payplan.pojo.dto.PayPlanDTO;
import com.xbongbong.pro.payplansheet.pojo.dto.batch.PayPlanSheetDTO;
import com.xbongbong.pro.payplansheet.pojo.vo.batch.PayPlanSheetAmountVO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/02/23 16:03
 */
@Service("purchaseFormDataUpdateServiceImpl")
public class PurchaseFormDataUpdateServiceImpl extends AbstractJxcUpdateDataService {

    private static final Logger LOG = LoggerFactory.getLogger(PurchaseFormDataUpdateServiceImpl.class);

    @Resource
    private UserHelp userHelp;
    @Resource
    private ProModelService proModelService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private PurchaseUserModel purchaseUserModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.PURCHASE.getCode());
    }
    @Override
    public void afterSaveLog(FormDataUpdateDTO formDataUpdateDTO, PaasFormEntityExt paasFormEntityExt, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.PURCHASE;
        boolean isCoverage = Objects.equals(1, formDataUpdateDTO.getIsCover());
        if(isCoverage){
           return;
        }
        // 记录日志

        StringBuilder sb = new StringBuilder();
        String memoName = paasFormEntityExt.getName();
        String userName = updateVO.getUserVO().getName();
        String opObjectName = paasFormDataEntity.getData().getString(PurchaseEnum.PURCHASE_NAME.getAttr());
        String serialNo = paasFormDataEntity.getSerialNo();
        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();

        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK), userName, memoName, opObjectName);

        saveLogger(formDataUpdateDTO, paasFormDataEntity, redundantTemplateTypeEnum, memo, opObjectName, OperateModuleTypeEnum.PURCHASE, updateVO, beforeUpdateVO,
                OperateTypeEnum.EDIT, IndexTypeEnum.IDX_SAAS_PURCHASE_SUB);

    }

    @Override
    public UpdateVO update(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            if ( Objects.equals(noApprovalRequired, 1) ) {
                JSONObject data = paasFormDataEntity.getData();
                data.remove(PurchaseEnum.ADD_PAYPLAN.getAttr());
                data.remove(PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr());
                data.remove(PurchaseEnum.ADD_PAY_SHEET.getAttr());
                paasFormDataEntity.setData(data);
                PurchaseEntityExt purchaseEntityExt = new PurchaseEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, purchaseEntityExt);
                // 关联产品特殊处理
                JSONObject purchaseDataList = purchaseEntityExt.getData();
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(purchaseDataList, PurchaseEnum.PRODUCT.getAttr());
                FormDataUtil.removeSystemData(purchaseDataList);
                Object richTextData = removeRichText(purchaseDataList);
                purchaseEntityExt.setData(purchaseDataList);
                updateLine = purchaseModel.update(purchaseEntityExt);
                purchaseEntityExt.getData().put(PurchaseEnum.PRODUCT.getAttr(),productArray);

                // 设置属性用于返回
                setPartialAttributes(purchaseEntityExt.getSubFormData(), purchaseEntityExt.getData(),
                        purchaseEntityExt.getUpdateTime(), purchaseEntityExt.getAddTime(), purchaseEntityExt.getSerialNo(),
                        purchaseEntityExt.getDepartmentId(), purchaseEntityExt.getOwnerId(),
                        paasFormDataEntity, beforeUpdateVO);
                //文件柜数据保存
                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
                //富文本数据更新
                updateFormRichText(formDataUpdateDTO, richTextData);
            }
            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public FormDataUpdateVO afterSave(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();

                BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
                packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                // 保存后的操作
                AfterSavePojo afterSavePojo = purchaseService.afterSave(saasFormSaveDTO);
                // 编辑付款计划、付款单
                Runnable runnable = () -> {
                    try {
                        editPayPlan(formDataUpdateDTO, beforeUpdateVO, updateVO);
                    } catch (Exception e) {
                        LOG.error("保存合采购同时保存付款", e);
                    }
                };
                threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);

                // 记录日志
                String serialNo = paasFormDataEntity.getSerialNo();
                // 采购合同编号数据一致性同步
                String oldSeriNo = oldPaasFormDataEntity.getSerialNo();
                if (!Objects.equals(oldSeriNo, serialNo)) {
                    ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, paasFormDataEntity.getId(), serialNo);
                    consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PURCHASE);
                }
                // 日志
                afterSaveLog(formDataUpdateDTO, paasFormEntity, paasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                // api发起
                apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);

                // 2021/3/3 业务规则
                activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else if (Objects.equals(noApprovalRequired, 2)) {
                // 自动拒绝
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            } else {
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                paasProcessDataEntity.setFormDataId(dataId);
                paasProcessDataEntity.setBusinessType(businessType);
                paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void apiHook(FormDataUpdateDTO formDataUpdateDTO, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        // 第三方服务
        lowCodeExecuteService(formDataUpdateDTO, updateVO, beforeUpdateVO);
    }
    /**
     * 编辑付款计划、付款单
     * @param formDataUpdateDTO
     * @param beforeUpdateVO
     * @param updateVO
     * @return void
     * @author 吴峰
     * @date 2021/3/15 11:11
     * @throws XbbException
     */
    private void editPayPlan(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO) throws XbbException{
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = beforeUpdateVO.getSaasNeedRedundantAttrPojo();
        if ( saasNeedRedundantAttrPoJo != null ) {
            PaasFormDataEntity paasFormDataEntity = updateVO.getPaasFormDataEntity();
            Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntity.getData(), PurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
            if ( saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
                PayPlanDTO payPlanDTO = new PayPlanDTO();
                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), payPlanDTO);
                payPlanDTO.setIsImport(formDataUpdateDTO.getIsImport());
                payPlanDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                payPlanService.payPlan(payPlanDTO);
            }
//            Double realPayPlanTotalAmount = 0.0D;
            if ( saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null ) {
                PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), payPlanSheetDTO);
                if (Objects.equals(updateVO.getNoApprovalRequired(), 1)) {
                    // 不走审批
                    payPlanSheetDTO.setProcessCreatorId(formDataUpdateDTO.getUserId());
                } else {
                    // 审批
                    payPlanSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                }
                PayPlanSheetAmountVO writeOffPrepaymentAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO, PaySheetTypeEnum.WRITE_OFF_PREPAY, supplierId);
//                realPayPlanTotalAmount = writeOffPrepaymentAmountVO.getRealPayTotalAmount();
            }
            if ( saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null ) {
                PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), payPlanSheetDTO);
                if (Objects.equals(updateVO.getNoApprovalRequired(), 1)) {
                    // 不走审批
                    payPlanSheetDTO.setProcessCreatorId(formDataUpdateDTO.getUserId());
                } else {
                    // 审批
                    payPlanSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                }
                PayPlanSheetAmountVO writeOffAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO, PaySheetTypeEnum.WRITE_OFF_PAY, supplierId);
//                Double addPaymentAmount = writeOffAmountVO.getRealPayTotalAmount();
//                realPayPlanTotalAmount = Arith.add(realPayPlanTotalAmount, addPaymentAmount);
            }
//            //todo chenshan2
//            if ( realPayPlanTotalAmount>0.0D ) {
//                purchaseService.updateProfit(formDataUpdateDTO.getCorpid(), realPayPlanTotalAmount, paasFormDataEntity.getId(), paasFormDataEntity);
//            }
        }
    }

    @Override
    public UpdateVO updateForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            JSONObject data = paasFormDataEntity.getData();
            JSONObject originData = (JSONObject) data.clone();
            data.remove(PurchaseEnum.ADD_PAYPLAN.getAttr());
            data.remove(PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr());
            data.remove(PurchaseEnum.ADD_PAY_SHEET.getAttr());
            paasFormDataEntity.setData(data);
            PurchaseEntityExt purchaseEntityExt = new PurchaseEntityExt();
            BeanUtil.copyProperties(paasFormDataEntity, purchaseEntityExt);
            // 关联产品特殊处理
            JSONObject purchaseDataList = purchaseEntityExt.getData();
            JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(purchaseDataList, PurchaseEnum.PRODUCT.getAttr());
            FormDataUtil.removeSystemData(purchaseDataList);
            Object richTextData = removeRichText(purchaseDataList);
            purchaseEntityExt.setData(purchaseDataList);
            updateLine = purchaseModel.update(purchaseEntityExt);
            purchaseEntityExt.getData().put(PurchaseEnum.PRODUCT.getAttr(),productArray);

            // 设置属性用于返回
            setPartialAttributes(purchaseEntityExt.getSubFormData(), purchaseEntityExt.getData(), purchaseEntityExt.getUpdateTime(), purchaseEntityExt.getAddTime(), purchaseEntityExt.getSerialNo(), purchaseEntityExt.getDepartmentId(), purchaseEntityExt.getOwnerId(), paasFormDataEntity, beforeUpdateVO);
            //文件柜数据保存
//            saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
            //富文本数据保存
            Integer updateRichTextLine = updateFormRichText(formDataUpdateDTO, richTextData);
            //表单数据和富文本数据其中有一个编辑就要进工作流
            updateLine = Objects.equals(updateLine, 1) || Objects.equals(updateRichTextLine, 1) ? 1 : 0;

            originData.put(PurchaseEnum.PRODUCT.getAttr(), productArray);
            paasFormDataEntity.setData(originData);
            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSaveForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();

            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
            // 保存后的操作
            purchaseService.afterSaveForUpdateWorkflow(saasFormSaveDTO);
            // 编辑付款计划、付款单
//            editPayPlan(formDataUpdateDTO, beforeUpdateVO, updateVO);
            // 记录日志
//            String serialNo = paasFormDataEntity.getSerialNo();
//            // 采购合同编号数据一致性同步
//            String oldSeriNo = oldPaasFormDataEntity.getSerialNo();
//            if (!Objects.equals(oldSeriNo, serialNo)) {
//                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, paasFormDataEntity.getId(), serialNo);
//                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PURCHASE);
//            }
            // 日志
//            afterSaveLog(formDataUpdateDTO, paasFormDataEntity, updateVO, beforeUpdateVO);
            // api发起
//            apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);
            // 2021/3/3 业务规则
//            activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);

            formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
//            PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//            paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//            paasProcessDataEntity.setFormDataId(dataId);
//            paasProcessDataEntity.setBusinessType(businessType);
//            paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
//            proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Long backupData(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) {
        String corpid = formDataUpdateDTO.getCorpid();
        Integer isApprove = paasFormEntity.getIsProcessForm();
        if (!formDataUpdateDTO.getIsSatisfyTrigger()) {
            return null;
        }
        JSONObject data = oldPaasFormDataEntity.getData();
        setSystemData(data, oldPaasFormDataEntity);
        long now = DateTimeUtil.getInt();
        data = backupDataOtherInfo(data, corpid, oldPaasFormDataEntity.getId());
        WorkflowBackupDataEntity workflowBackupDataEntity = new WorkflowBackupDataEntity(corpid, oldPaasFormDataEntity.getAppId(), oldPaasFormDataEntity.getFormId(), oldPaasFormDataEntity.getMenuId(), 0L, 0L,
                oldPaasFormDataEntity.getId(), data, now, now, DelEnum.NORMAL.getDel());
        workflowBackupDataModel.insert(workflowBackupDataEntity);
        //富文本数据备份
        backupRichText(workflowBackupDataEntity, formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
        return workflowBackupDataEntity.getId();
    }

    @Override
    public JSONObject backupDataOtherInfo(JSONObject data, String corpid, Long dataId) {
        List<PurchaseUserEntity> contactList = purchaseUserModel.getPurchaseUserListByPurchaseId(corpid, dataId, null);
        data.put(StringConstant.USER_TEAM, contactList);
        List<PurchaseProductEntity> productList = purchaseProductModel.getProductsByPurchaseId(corpid, dataId);
        data.put(StringConstant.PRODUCT, productList);
        return data;
    }
}
